package com.itsu.compoment.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itsu.compoment.socket.Message;
import com.itsu.compoment.socket.MyWebSocketHandler;
import com.itsu.dao.MessageDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * @author 苏犇
 * @create time 2019/12/7 1:05
 */
@Component
@Slf4j
public class MessagePushTask {

    @Resource
    private MessageDAO messageDAO;

    @Scheduled(cron = "0/5 * * * * ? ")
    public void sendMessage() {
        System.err.println("task start ... ");
        QueryWrapper<Message> condition = new QueryWrapper<>();
        condition.eq("stat", "N");
        List<Message> messages = messageDAO.selectList(condition);
        Set<String> loginUsers = MyWebSocketHandler.getLoginUsers();
        for (Message message : messages) {
            if (loginUsers.contains(message.getToUserId())) {
                TextMessage msg = new TextMessage(JSON.toJSONString(message));
                MyWebSocketHandler.sendMessageToUser(message.getToUserId(), msg);
                log.info("message send ... : {}", JSON.toJSONStringWithDateFormat(message, "yyyy-MM-dd hh:mm:ss"));
                message.setStat("Y");
                messageDAO.update(message, null);
            }
        }
    }
}
